﻿using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using LZ.HzStorage.EntityFrameworkCore.Seed;
using Abp.Configuration.Startup;
using Abp.EntityFrameworkCore;
using Abp.Domain.Uow;
using LZ.DCode;

namespace LZ.HzStorage.EntityFrameworkCore
{
    [DependsOn(
        typeof(DCodeCoreModule),
        typeof(AbpZeroCoreEntityFrameworkCoreModule))]
    public class HzStorageEntityFrameworkModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }
        public override void PreInitialize()
        {
            base.PreInitialize();
            Configuration.ReplaceService<IConnectionStringResolver, ConnectionStringResolver>();
            this.AddDbContext<HzStorageDbContext>();//���ݿ�һ
            this.AddDbContext<HzGKPlatformDbContext>();//���ݿ��
        }
        private void AddDbContext<TDbContext>()
            where TDbContext : AbpDbContext
        {
            Configuration.Modules.AbpEfCore().AddDbContext<TDbContext>(options =>
            {
                if (options.ExistingConnection != null)
                {
                    HzStorageDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                }
                else
                {
                    HzStorageDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                }
            });
        }

        //public override void PreInitialize()
        //{
        //    if (!SkipDbContextRegistration)
        //    {
        //        Configuration.Modules.AbpEfCore().AddDbContext<HzStorageDbContext>(options =>
        //        {
        //            if (options.ExistingConnection != null)
        //            {
        //                HzStorageDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
        //            }
        //            else
        //            {
        //                HzStorageDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
        //            }
        //        });
        //    }
        //}

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(HzStorageEntityFrameworkModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }
}

